from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from NetShop.models import Address,CustomLogin
from PetNetadmin.serializers import ChargeAddressSerializer


class ChargeAddress(APIView):
    def get(self, request):
        # print(request.GET.get('id'))
        custom_id = request.GET.get('id')
        info = Address.objects.filter(custom_id=custom_id)
        serializer = ChargeAddressSerializer(info, many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return Response(result, status=status.HTTP_200_OK)

    # 编辑好的数据重新提交
    def post(self, request):
        print('编辑',request.data)
        id = request.data['id']
        is_default = request.data['is_default']
        custom = request.data['custom_id']
        name = request.data['name']
        address = Address.objects.get(id=id)
        if is_default:
            # 其他置为false
            Address.objects.filter(custom_id=custom).update(is_default=False)
        serializer = ChargeAddressSerializer(address, data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = {
                'code': 2000,
                'msg': '更新成功'
            }
            return Response(result, status=status.HTTP_200_OK)
        return Response({'msg': '更新失败'}, status=status.HTTP_404_BAD_REQUEST)

# 添加地址
@api_view(['POST'])
def addAddressInfo(request):
    print('添加',request.data)
    custom_id = request.data['custom_id']
    detail = request.data['detail']
    name = request.data['name']
    is_default = request.data['is_default']
    basic_address = request.data['basic_address']
    adpca = request.data['adpca']
    data = {
        'mobile':request.data['mobile'],
        'adpca': adpca[2],
        'province':basic_address['province'],
        'city':basic_address['city'],
        'region':basic_address['region'],
        'detail':detail,
        'is_default':is_default,
        'custom_id':custom_id,
        'name':name
    }
    print(data)
    if detail is None or name is None:
        return Response({'msg':'填写不能为空'},status=status.HTTP_404_NOT_FOUND)
    if is_default:
        Address.objects.filter(custom_id=custom_id).update(is_default=False)
    serializer =ChargeAddressSerializer(data=data,partial=True)
    if serializer.is_valid(raise_exception=True):
        serializer.save()
        result = {
            'code': 2000,
            'msg': '更新成功'
        }
        return Response(result, status=status.HTTP_200_OK)
    return Response({'msg':'创建失败'},status=status.HTTP_404_NOT_FOUND)

# 删除地址
@api_view(['POST'])
def deleteAddress(request,id):
    AddressMsg = Address.objects.get(id=id)
    AddressMsg.delete()
    result = {
        'code': 2000,
        'msg': '删除成功'
    }
    return Response(result, status=status.HTTP_200_OK)
